import Config from '../config/config';
import Bus from './bus';

// fixme for debugging
console.info('router-guard.js is loading');

var vue;
var bus;
var keyStorePath = Config.auth.keyStorePath || 'Please-Set-Key-Store-Url-Inside-Config-js';

export default {
    loadRouter: function (router) {

        // note here you can customize the router guard. This process will be called only once.
        // router.afterEach(...);

        // note here this route has side effect, so it should not be put inside router.js
        router.beforeEach(function (to, from, next) {
            if (to.path === keyStorePath) {
                // note keystore is the entry point for token initialization
                var token = to.query.token;
                if (token) {
                    // save token to shared object
                    bus.token = token;
                }
                next({
                    // todo there can be more targets
                    path: '/',
                    replace: true,
                });
            }
            next();
        });
    },

    // contract method for vue plugins
    install: function (Vue, options) {
        vue = Vue;
        if (!Vue.prototype.$bus) {
            Vue.use(Bus);
        }
        bus = Vue.prototype.$bus;
    },
};